package cc.rengu.igas.channel.cups.core.service.trans;


import cc.rengu.igas.channel.cups.common.constant.CupsConfigConstant;
import cc.rengu.igas.channel.cups.common.constant.CupsParamConstant;
import cc.rengu.igas.channel.cups.common.constant.CupsTreeNodeConstant;
import cc.rengu.igas.channel.cups.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.cups.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.cups.core.model.CupsField;
import cc.rengu.igas.channel.cups.core.model.CupsFieldBean;
import cc.rengu.igas.channel.cups.core.model.CupsFieldRspBean;
import cc.rengu.igas.channel.cups.core.realize.CupsMacService;
import cc.rengu.igas.channel.cups.core.realize.impl.CupsMacServiceImpl;
import cc.rengu.igas.channel.cups.core.service.base.RevsalService;
import cc.rengu.igas.channel.cups.facade.request.PreAuthRevsalRequest;
import cc.rengu.igas.channel.cups.facade.response.PreAuthRevsalResponse;
import cc.rengu.igas.share.common.util.DateShareUtil;
import cc.rengu.jradp.mods.trmsg.iso8583.MacUtil;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelInfo;
import cc.rengu.oltp.service.common.entity.KeyInfo;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.cache.UnifiedCache;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * 预授权冲正
 */
public class CupsPreAuthRevsalService extends RevsalService {

    @Override
    protected Object beforeBizProcess() throws Exception {
        PreAuthRevsalRequest preAuthRevsalRequest = new PreAuthRevsalRequest();
        ConvertUtil.convertOutput(preAuthRevsalRequest);
        return preAuthRevsalRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        PreAuthRevsalRequest preAuthRevsalRequest = (PreAuthRevsalRequest) request;
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(preAuthRevsalRequest.getHeader().getInstId(),
                CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_DIRECT_FLAG);
        if (sysParam == null) {
            /*未配置默认间连*/
            return inDirectCups(preAuthRevsalRequest);
        } else if (AppParamConstant.YES.equals(sysParam.getParamValue())) {
            return directCups(preAuthRevsalRequest);
        } else {
            return inDirectCups(preAuthRevsalRequest);
        }
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        PreAuthRevsalResponse preAuthRevsalResponse = (PreAuthRevsalResponse) response.getResult();
        ConvertUtil.convertInput(preAuthRevsalResponse);
    }

    /**
     * 直连cups
     *
     * @param preAuthRevsalRequest
     * @return
     * @throws Exception
     */
    ChnlBizResponse directCups(PreAuthRevsalRequest preAuthRevsalRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        String algorithm = null;
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        PreAuthRevsalResponse preAuthRevsalResponse = new PreAuthRevsalResponse();
        String instId = preAuthRevsalRequest.getHeader().getInstId();

        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(CupsTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(instId,
                CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_ALG_TYPE);
        if (sysParam == null) {
            algorithm = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_ALG_TYPE);
        } else {
            algorithm = sysParam.getParamValue();
        }
        String termType = null;
        CupsField cupsField = new CupsField();
        //由于名称一致，因此authCode也在此处拷贝接入到cupsField
        BeanUtil.beanCopy(preAuthRevsalRequest, cupsField);
        cupsField.setMsgType("0420");
        cupsField.setProcCode("030000");
        cupsField.setLocalDate(preAuthRevsalRequest.getHeader().getTransDate().substring(4, 8));
        cupsField.setLocalTime(preAuthRevsalRequest.getHeader().getTransTime());
        cupsField.setCupsInstCode(preAuthRevsalRequest.getCupsInstCode());
        cupsField.setAcqInstCode(preAuthRevsalRequest.getCupsInstCode());
        cupsField.setFwdInstCode(preAuthRevsalRequest.getFwdInstCode());
        cupsField.setTransDateTime(preAuthRevsalRequest.getTransDateTime());
        cupsField.setConCode("06");
        cupsField.setMchntNo(cupsField.getCupsMchntNo());
        String tmpAmt = AmountUtil.changeY2F(preAuthRevsalRequest.getOrderAmt());
        cupsField.setOrderAmt(String.format("%012d", Integer.valueOf(tmpAmt)));
        if (preAuthRevsalRequest.getTermInfo() != null) {
            termType = preAuthRevsalRequest.getTermInfo().getDeviceType();
        }
        String reseved = packF060Field("4021", preAuthRevsalRequest.getTermRead(), preAuthRevsalRequest.getIcConCode(),
                null, null, preAuthRevsalRequest.getTermInfo().getDeviceType(), algorithm);
        cupsField.setReseved(reseved);
        String origAcqInstIdCode = preAuthRevsalRequest.getCupsInstCode();
        if (origAcqInstIdCode.length() < 11) {
            origAcqInstIdCode = String.format("%0" + (11 - origAcqInstIdCode.length()) + "d", 0) + origAcqInstIdCode;
        }
        String origFwdInstCode = preAuthRevsalRequest.getFwdInstCode();
        if (origFwdInstCode.length() < 11) {
            origFwdInstCode = String.format("%0" + (11 - origFwdInstCode.length()) + "d", 0) + origFwdInstCode;
        }
        cupsField.setOrigData("0200" + preAuthRevsalRequest.getOrigTxnInfo().getOriCupsTraceNo() +
                preAuthRevsalRequest.getOrigTxnInfo().getOriTransDateTime() +
                origAcqInstIdCode + origFwdInstCode);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.CUPS_MACBLOCK_ORIG_DATA_ELEMTS, cupsField.getOrigData().substring(0, 20));
        CupsFieldBean cupsFieldBean = new CupsFieldBean();
        cupsFieldBean.setCupsField(cupsField);
        ConvertUtil.convertInput(cupsFieldBean);
        /*计算macblock*/
        MacUtil commonMac = (MacUtil) UnifiedCache.get(CupsParamConstant.CUPS_8583_MAC_CACHE_NAME,
                CupsParamConstant.CUPS_8583_MAC_FILE +
                        CupsParamConstant.CUPS_8583_MAC_TYPE_COMMON);
        byte[] macBlock = commonMac.genMacBlock(CupsParamConstant.CUPS_8583_MAC_TYPE_COMMON);
        if (macBlock == null) {
            throw new BizException(RespCodeEnum.GENERATE_MAC_BLOCK_ERROR.getRespCode(), RespCodeEnum.GENERATE_MAC_BLOCK_ERROR.getRespDesc());
        }
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.CUPS_MAC_BLOCK, new String(macBlock));

        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, preAuthRevsalRequest.getHeader().getTxnNum());
        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);
        if (98 == iReturnCode) {
            rglog.error("调用银联cups服务<{}>超时，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            preAuthRevsalResponse.setRespCode("98");
            preAuthRevsalResponse.setRespDesc("交易状态未明");
            chnlBizResponse.setResult(preAuthRevsalResponse);
            return chnlBizResponse;
        } else if (0 != iReturnCode) {
            rglog.error("调用银联全渠道服务<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        /*还原交易码*/
        String tunlSsn = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.CHANNEL_SEQ_NUM);
        UnifiedCache.remove(CupsParamConstant.CACHE_CUPS_SN, tunlSsn);
        if (0 != iReturnCode) {
            rglog.error("调用银联cups服务失败，iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        CupsFieldRspBean cupsFieldRspBean = new CupsFieldRspBean();
        ConvertUtil.convertOutput(cupsFieldRspBean);
        String mac = cupsFieldRspBean.getCupsFieldRsp().getMac();
        /*生成应答macBlock*/
        byte[] macBlockRsp = commonMac.getMacBlock(CupsParamConstant.CUPS_8583_MAC_TYPE_COMMON);
        CupsMacService cupsMacService = new CupsMacServiceImpl();
        KeyInfo keyInfo = (KeyInfo) xmlTreeUtil.getXmlTreeObjectValue(CupsTreeNodeConstant.CUPS_MAC_KEY_INFO, KeyInfo.class);
        boolean flag = cupsMacService.verifyMacString(keyInfo, mac, new String(macBlockRsp));
        if (!flag) {
            rglog.error("验证mac失败");
            throw new BizException(RespCodeEnum.VERIFY_MAC_ERROR.getRespCode(), RespCodeEnum.VERIFY_MAC_ERROR.getRespDesc());
        }

        BeanUtil.beanCopy(cupsFieldRspBean.getCupsFieldRsp(), preAuthRevsalResponse);
        preAuthRevsalResponse.setRespCode(cupsFieldRspBean.getCupsFieldRsp().getRespCode());
        if (CupsParamConstant.SUCCESS_CODE.equals(preAuthRevsalResponse.getRespCode())) {
            preAuthRevsalResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            preAuthRevsalResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        }
        chnlBizResponse.setResult(preAuthRevsalResponse);
        return chnlBizResponse;
    }

    /**
     * 间联cups
     *
     * @param preAuthRevsalRequest
     * @return
     * @throws Exception
     */
    ChnlBizResponse inDirectCups(PreAuthRevsalRequest preAuthRevsalRequest) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        String algorithm = null;
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        PreAuthRevsalResponse preAuthRevsalResponse = new PreAuthRevsalResponse();
        String traceNo = preAuthRevsalRequest.getHeader().getTraceNo();
        String instId = preAuthRevsalRequest.getHeader().getInstId();
        String oriTraceNo = preAuthRevsalRequest.getOrigTxnInfo().getOriTraceNo();
        /* 流水号规则：8位渠道标识 + 8位日期 + 6位时间 + 2位数据库服务器集群标识 + 2位预留位 + 6位序号 + 调用序号 */
       /* String transDateTime= traceNo.substring(12,22);
        String cupsSsn = traceNo.substring(26,32);
        String channelSeqNum = genServiceSn(instId,traceNo);*/
        String cupsSsn = traceNo.substring(traceNo.length() - 6);
        rglog.info("cupsSsn = <{}>", cupsSsn);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.SERVICE_SN, traceNo);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.ORI_SERVICE_SN, oriTraceNo);
        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(CupsTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(instId,
                CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_ALG_TYPE);
        if (sysParam == null) {
            algorithm = XmlConfigUtil.getXmlConfigCacheKeyValue(CupsConfigConstant.CUPS_CONF_NODE, CupsConfigConstant.CUPS_ALG_TYPE);
        } else {
            algorithm = sysParam.getParamValue();
        }
        String termType = null;
        CupsField cupsField = new CupsField();
        BeanUtil.beanCopy(preAuthRevsalRequest, cupsField);

        if (preAuthRevsalRequest.getTermInfo() != null) {
            termType = preAuthRevsalRequest.getTermInfo().getDeviceType();
        }
        if (preAuthRevsalRequest.getIcData() != null && !preAuthRevsalRequest.getIcData().isEmpty()) {
            String icDataLenth = Integer.toHexString(preAuthRevsalRequest.getIcData().length()).length() == 1
                    ? "0" + Integer.toHexString(preAuthRevsalRequest.getIcData().length()).toUpperCase() : Integer.toHexString(preAuthRevsalRequest.getIcData().length()).toUpperCase();
            xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.IC_DATA_LENGTH, icDataLenth);
        }
        String reseved = packF060Field("4021", preAuthRevsalRequest.getTermRead(), preAuthRevsalRequest.getIcConCode(),
                null, null, preAuthRevsalRequest.getTermInfo().getDeviceType(), algorithm);
        cupsField.setReseved(reseved);

        CupsFieldBean cupsFieldBean = new CupsFieldBean();
        cupsFieldBean.setCupsField(cupsField);
        ConvertUtil.convertInput(cupsFieldBean);
        /*branchId*/
        if (preAuthRevsalRequest.getAcqReserved() == null) {
            rglog.error("必须上送branchId");
            throw new BizException(RespCodeEnum.REQUEST_MSG_ERROR.getRespCode(), RespCodeEnum.REQUEST_MSG_ERROR.getRespDesc());
        } else {
            Map<String, Object> reqMap = JSONObject.parseObject(preAuthRevsalRequest.getAcqReserved());
            for (Map.Entry req : reqMap.entrySet()) {
                xmlTreeUtil.setXmlTreeStringValue((String) req.getKey(), (String) req.getValue());
            }
        }
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.ESB_ORDER_AMT, StringUtil.leftFillZero(AmountUtil.changeY2F(preAuthRevsalRequest.getOrderAmt()), CupsParamConstant.AMOUNT_LENGTH));
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.SERVICE_ID, preAuthRevsalRequest.getHeader().getTxnNum());
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.REQUESTER_ID, CupsParamConstant.REQUEST_ID);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.VERSION_ID, CupsParamConstant.VERSION_ID);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.CHANNEL_ID, CupsParamConstant.CHANNEL_ID);
        xmlTreeUtil.setXmlTreeStringValue(CupsTreeNodeConstant.SERVICE_TIME, preAuthRevsalRequest.getHeader().getTransDate() + preAuthRevsalRequest.getHeader().getTransTime());
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, preAuthRevsalRequest.getHeader().getTxnNum());
        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);
        if (98 == iReturnCode) {
            rglog.error("调用银联cups服务<{}>超时，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            preAuthRevsalResponse.setRespCode("98");
            preAuthRevsalResponse.setRespDesc("交易状态未明");
            chnlBizResponse.setResult(preAuthRevsalResponse);
            return chnlBizResponse;
        } else if (0 != iReturnCode) {
            rglog.error("调用银联全渠道服务<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }

        CupsFieldRspBean cupsFieldRspBean = new CupsFieldRspBean();
        ConvertUtil.convertOutput(cupsFieldRspBean);
        String esbStatus = xmlTreeUtil.getXmlTreeStringValue(CupsTreeNodeConstant.ESB_STATUS);
        rglog.info("esbStatus=<{}>", esbStatus);
        if ("COMPLETE".equals(esbStatus)) {
            //ESB成功
            preAuthRevsalResponse.setRespCode(CupsParamConstant.SUCCESS_CODE);
            BeanUtil.beanCopy(cupsFieldRspBean.getCupsFieldRsp(), preAuthRevsalResponse);
        } else if ("FAIL".equals(esbStatus)) {
            //ESB失败
            preAuthRevsalResponse.setRespCode(xmlTreeUtil.getXmlTreeStringValue(CupsTreeNodeConstant.ESB_RSP_CODE));
            preAuthRevsalResponse.setRespDesc(xmlTreeUtil.getXmlTreeStringValue(CupsTreeNodeConstant.ESB_RSP_DESC));
        }
        if (preAuthRevsalResponse.getSettleDate() != null) {
            preAuthRevsalResponse.setSettleDate(DateShareUtil.changeDate4To8(preAuthRevsalResponse.getSettleDate()));
        }
        if (CupsParamConstant.SUCCESS_CODE.equals(preAuthRevsalResponse.getRespCode())) {
            preAuthRevsalResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            preAuthRevsalResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        }
        chnlBizResponse.setResult(preAuthRevsalResponse);
        return chnlBizResponse;
    }
}
